﻿using System;
using System.Text;

namespace TY.UC.Common
{

    /// <summary>
    /// 订单号生成类
    /// </summary>
    public class OrderHelper
    {
        private static readonly char[] Letter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
        private static readonly object Obj = new object();
        private static readonly string Digits = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";

        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <returns></returns>
        public static string GenerateOrderNo()
        {
            return GenerateOrder(4);
        }

        /// <summary>
        /// 生成订单号，纯数字(10位)
        /// created by 黄星星 on 2016-9-18
        /// </summary>
        /// <returns></returns>
        public static string GenerateTenDigitsOrderNo()
        {
            return GenerateDigitsOrder(0);
        }

        /// <summary>
        /// 生成付款流水号
        /// </summary>
        /// <returns></returns>
        public static string GeneratePayNo()
        {
            return "P"+GenerateOrder(4);
        }

        public static string GenerateOrder(int lenght)
        {
            lock (Obj)
            {
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return GetRandomString(lenght) + Convert.ToInt64(ts.TotalSeconds).ToString();
            }
        }
        /// <summary>
        /// 纯数字
        /// </summary>
        /// <param name="lenght"></param>
        /// <returns></returns>
        public static string GenerateDigitsOrder(int lenght)
        {
            lock (Obj)
            {
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return GenerateRandomCode(lenght) + Convert.ToInt64(ts.TotalSeconds).ToString();
            }
        }

        private static string GetRandomString(int lenght)
        {
            StringBuilder strRandom = new StringBuilder();
            for (int i = 0; i < lenght; i++)
            { 
                strRandom.Append(Letter[new Random(Guid.NewGuid().GetHashCode()).Next(26)]);
            }
            return strRandom.ToString();
        }

        /// <summary>
        /// 随机生成指定长度的码（纯数字）
        /// </summary>
        /// <returns></returns>
        public static string GenerateRandomCode(int n)
        {
            string code = "";
            int len = Digits.Length;
             
            lock (Obj)
            {
                for (int i = 0; i < n; i++)
              {
                  code += Digits[new Random(Guid.NewGuid().GetHashCode()).Next(len)];
               } 
            } 
            return code;
        }
    }
}